package com.cyzy.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cyzy.dto.ResponseDto;
import com.cyzy.pojo.Driver;
import com.cyzy.pojo.TripOrder;
import com.cyzy.service.DriverService;
import com.cyzy.utils.CodeUtils;
import com.cyzy.utils.RedisUtil;
import org.jacoco.agent.rt.internal_035b120.Offline;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Map;


@RestController
@RequestMapping("/driver")
public class DriverController {

    @Autowired
    private DriverService driverService;

    @Autowired
    private CodeUtils codeUtils;

    @Autowired
    private RedisUtil redisUtil;


    @GetMapping("/getCode")
    public ResponseDto getCode(@RequestParam("key") String key){
        System.out.println(key+ " -----key");
        //生成验证码和图片
        String codeBase64 = codeUtils.getRandomCodeImage();
        String code = codeUtils.getCode();
        //存储验证码到redis
        redisUtil.set(key, code);
        redisUtil.setExpire(key,300);
        return ResponseDto.ok(codeBase64);
    }

    @PostMapping("/login")
    public ResponseDto login(@RequestBody Driver driver,@RequestParam("key") String key,@RequestParam("code") String code) {
        //从redis获取验证码code
        String verification = redisUtil.get(key);
        //先判断验证码是否正确
        if(!code.equalsIgnoreCase(verification)){
            return ResponseDto.fail("验证码过期或有误！");
        }
        //获取账号密码对比数据库
        String acc=driver.getDriverAcc();
        String password=driver.getPassword();
        System.out.println(driver+"--------------"+key+"--------"+code);
        if(acc==null || password==null){
            return ResponseDto.fail("账号密码不能为空！");
        }
        //返回结果集
        Map<String,Object> result=driverService.login(acc,password);
        //结果集为空返回错误
        if(result==null){
            return ResponseDto.fail("账号或密码有误！");
        }
        return ResponseDto.ok(result);
    }

    @PostMapping("/register")
    public ResponseDto register(@RequestBody Driver driver){
        System.out.println(driver+"----------driver--------");
        if(driver==null){
            return ResponseDto.fail("注册数据不能为空！");
        }
        if (driver.getPhone() == null || driver.getPassword() == null) {
            return ResponseDto.fail("手机号和密码不能为空！");
        }
        return driverService.register(driver);
    }

    @GetMapping("/getDriverType")
    public ResponseDto getDriverType(@RequestParam("driverId") int driverId){
        int typeId=driverService.selectDriverType(driverId);
        return ResponseDto.ok(typeId);
    }

    //验证手机和验证码是否正确
    @GetMapping("/phoneLogin")
    public ResponseDto phoneLogin(@RequestParam("phone") String phone,@RequestParam("code") String code){

        System.out.println("phone：：" + phone + " ;  code:: " + code);

        String codeNew = redisUtil.get(phone);

        if(codeNew.equals(code)){
            return ResponseDto.ok("登陆成功");
        }
        return ResponseDto.fail("验证码输入错误！");
    }

    //生成短信验证码
    @GetMapping("/getPhoneCode")
    public ResponseDto getPhoneCode(@RequestParam("phone") String phone){
        String message;
        try {
            message = driverService.getPhoneCode(phone);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return ResponseDto.ok(message);
    }

    //忘记密码重新设置密码
    @GetMapping("/forgotPassword")
    public ResponseDto forgotPassword(@RequestParam("code")String code,@RequestParam("phone")String phone,@RequestParam("driverId")long driverId,@RequestParam("password")String password){


        System.out.println(driverId + " ---------driverId");
        System.out.println(password + " ----password");

        if(driverId == 0 || password == null || code == null || phone == null){
            return ResponseDto.fail("用户Id或密码不能为空！");
        }
        String codeNew = redisUtil.get(phone);
        if(!codeNew.equals(code)){
            return ResponseDto.fail("验证码错误！");
        }
        driverService.forgotPassword(driverId,password);
        return ResponseDto.ok("重置成功");
    }

    //退出
    @GetMapping("/logout")
    public ResponseDto logout(@RequestParam("token") String token){
        if(token==null){
            return ResponseDto.ok("token为空！");
        }
        //删除token
        if(!redisUtil.del(token)){
            return ResponseDto.fail("删除token失败！");
        }
        return ResponseDto.ok("删除token成功！");
    }

    //系统自动派单给司机
    @PostMapping("/automaticOrder")
    public ResponseDto automaticOrder(@RequestParam("orderId") Long orderId){
        System.out.println("订单编号：" + orderId);
        String message =  driverService.automaticOrder(orderId);
        return ResponseDto.ok(message);
    }

    //司机传入自己的 ID，从 Redis 获取订单数据
    @GetMapping("/getDriverOrders")
    public ResponseDto getDriverOrders(@RequestParam("driverId") String driverId){
        System.out.println(driverId + "  --driverId");
        String key = "driversOrder:" + driverId;
        String orderJson = redisUtil.get(key);
        if (orderJson != null) {
            TripOrder order = JSON.parseObject(orderJson, TripOrder.class);
            return ResponseDto.ok(order);
        } else {
            return ResponseDto.ok(Collections.emptyMap());
        }
    }

    @PutMapping("/updateDriverTakingStatus")
    public ResponseDto updateDriverTakingStatus(@RequestParam("driverId") int driverId,
                                                @RequestParam("takingStatus") int takingStatus){
        System.out.println(driverId);
        System.out.println(takingStatus);
        LambdaUpdateWrapper<Driver> wrapper=new LambdaUpdateWrapper<Driver>()
                .eq(Driver::getDriverId,driverId)
                .set(Driver::getTakingStatus,takingStatus);
        boolean flag = driverService.update(wrapper);
        if(!flag){
            return ResponseDto.fail("修改失败！");
        }
        return ResponseDto.ok("修改成功！");
    }

    //司机上线/下线
    @PostMapping("/driverStatus")
    public ResponseDto driverStatus(@RequestBody Driver driver){
        System.out.println(driver + " driver");
        //下线
        if(driver.getDriverX() == 0 || driver.getDriverY() == 0){
            driverService.Offline(driver);
         return   ResponseDto.ok("司机下线成功！");
        }
        driverService.upline(driver);
        return ResponseDto.ok("司机上线成功！");
    }
    //通过订单号查询司机
    @GetMapping("/getDriver")
    public ResponseDto getDriver(@RequestParam("orderId") String orderId){
        System.out.println(orderId +" ----orderId");
        Driver driver = driverService.getDriverByOrderId(orderId);
        if(driver == null){
            return ResponseDto.fail("查询失败");
        }
        return ResponseDto.ok(driver);
    }
}
